package com.org.handler;

import com.google.gson.Gson;
import com.org.Msg.Msg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 注销的时候处理情况
 */
@Component
public class AuthenticationLogout implements LogoutSuccessHandler {

    @Autowired
    Gson gson;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String token = request.getHeader("token");
        Msg result=null;
        try {
            if(token==null){
                //token为空表示未登录,注销失败
                result=Msg.fail("未登录，不能进行注销操作！！！");
            }else{
                String username = stringRedisTemplate.opsForValue().get(token);
                if(username==null){
                    //token不正确,注销失败
                    result=Msg.fail("登录凭证异常，注销失败！！！");
                }else{
                    //token正确,注销成功
                    result=Msg.success("注销成功");
                    //清空token
                    stringRedisTemplate.delete(token);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        response.setContentType("application/json;charset=utf-8");  //设置编码格式
        response.getWriter().write(gson.toJson(result));    //返回给前端
    }
}
